#!/bin/bash

# 日志记录函数
log() {
    echo "[$(date '+%Y-%m-%d %T')] $1" | tee -a /var/log/nic_auto_tune.log
}


# 检查ethtool是否存在
install_ethtool() {
    if ! command -v ethtool &> /dev/null; then
        log "安装ethtool工具..."
        if command -v apt-get &> /dev/null; then
            apt-get install -y ethtool > /dev/null 2>&1
        elif command -v yum &> /dev/null; then
            yum install -y ethtool > /dev/null 2>&1
        elif command -v dnf &> /dev/null; then
            dnf install -y ethtool > /dev/null 2>&1
        else
            log "错误：不支持的包管理器，请手动安装ethtool"
            exit 2
        fi
        log "ethtool安装完成"
    fi
}

# 自动检测主物理网卡
detect_primary_nic() {
    # 获取默认路由对应的网卡
    local route_nic=$(ip route show default | awk '/default/ {print $5}')
    
    # 获取物理网卡列表（排除虚拟设备）
    local physical_nics=$(ls /sys/class/net | grep -vE 'lo|virbr|docker|veth|br-')
    
    # 优先选择有默认路由的物理网卡
    if [[ -n "$route_nic" ]] && [[ $physical_nics =~ $route_nic ]]; then
        echo "$route_nic"
        return
    fi
    
    # 次选第一个启用的物理网卡
    for nic in $physical_nics; do
        if [[ $(cat /sys/class/net/$nic/operstate) == "up" ]]; then
            echo "$nic"
            return
        fi
    done
    
    # 最后选择第一个物理网卡
    echo "$physical_nics" | head -1
}

# 安全降速函数
safe_downgrade() {
    local interface=$1
    local target_speed=${2:-100}   # 默认100Mbps
    local target_duplex=${3:-half} # 默认半双工
    
    # 验证网卡存在
    if [[ ! -d /sys/class/net/$interface ]]; then
        log "错误：网卡 $interface 不存在"
        return 3
    fi
    
    # 获取当前设置
    local current_setting=$(ethtool $interface 2>/dev/null | grep -E "Speed|Duplex")
    log "当前设置 [$interface]: $current_setting"
    
    # 获取支持的速率
    local supported_speeds=$(ethtool $interface 2>/dev/null | sed -n '/Supported link modes:/,/Advertised link modes:/p' | grep -oE '[0-9]+base[^ ]+')
    
    # 智能选择最佳降速模式
    local selected_speed=$target_speed
    if [[ ! "$supported_speeds" =~ "${target_speed}base" ]]; then
        log "警告：网卡不支持 ${target_speed}Mbps 模式，尝试兼容模式"
        
        # 尝试寻找最佳兼容速率
        local compatible_speeds="1000 100 10"
        for speed in $compatible_speeds; do
            if [[ "$supported_speeds" =~ "${speed}base" ]]; then
                selected_speed=$speed
                log "选择兼容速率：${speed}Mbps"
                break
            fi
        done
    fi
    
    # 执行降速操作
    log "配置降速 [$interface]: ${selected_speed}Mbps/$target_duplex"
    if ethtool -s $interface speed $selected_speed duplex $target_duplex >/dev/null 2>&1; then
        # 验证新设置
        local new_setting=$(ethtool $interface 2>/dev/null | grep -E "Speed|Duplex")
        log "新设置 [$interface]: $new_setting"
        
        # 检查是否生效
        if ! grep -q "${selected_speed}Mb/s" <<< "$new_setting"; then
            log "警告：速度未生效，尝试重启网卡..."
            ip link set $interface down && ip link set $interface up
            sleep 2
            new_setting=$(ethtool $interface 2>/dev/null | grep -E "Speed|Duplex")
            log "重启后状态: $new_setting"
        fi
    else
        log "错误：配置失败，尝试关闭网卡后重试..."
        ip link set $interface down
        ethtool -s $interface speed $selected_speed duplex $target_duplex
        ip link set $interface up
        sleep 2
        new_setting=$(ethtool $interface 2>/dev/null | grep -E "Speed|Duplex")
        log "最终状态: $new_setting"
    fi
}

# 主程序
main() {
    install_ethtool
    
    # 自动检测主网卡
    local primary_nic=$(detect_primary_nic)
    
    if [[ -z "$primary_nic" ]]; then
        log "错误：未找到可用物理网卡"
        exit 3
    fi
    
    log "检测到主网卡: $primary_nic"
    
    # 执行安全降速
    safe_downgrade $primary_nic
    
    log "操作完成，详细日志见 /var/log/nic_auto_tune.log"
}

# 执行主程序
main